<template>
  <el-dialog :title="`${row?.id ? '编辑' : '新增'}部门`" :model-value="modelValue" width="700px" @close="commEvent.onClose">
    <el-form ref="formRef" :model="formValue" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="上级部门" prop="pid">
            <el-tree-select
              v-model="formValue.pid"
              :data="depts"
              node-key="id"
              check-strictly
              default-expand-all
              :render-after-expand="false"
              :expand-on-click-node="false"
              :check-on-click-node="true"
              :props="{ label: 'name', value: 'id' }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="formValue.name" placeholder="请输入部门名称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示排序" prop="sort">
            <el-input-number v-model="formValue.sort" :min="1" :max="9999" controls-position="right"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门领导" prop="leader">
            <el-input v-model="formValue.leader" placeholder="请输入部门领导" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门状态" prop="status">
            <el-radio-group v-model="formValue.status">
              <el-radio v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="phone">
            <el-input v-model="formValue.phone" placeholder="请输入联系方式" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱地址" prop="email">
            <el-input v-model="formValue.email" placeholder="请输入邮箱地址" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="commEvent.onClose">取消</el-button>
      <el-button type="primary" @click="commEvent.onSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, PropType, watch, nextTick } from "vue"
import { ElMessage, FormInstance, FormRules } from "element-plus"
import { statusOptions } from "@/utils/dict"
import { addDeptApi } from "@/api/modules/system"
import { SystemSpace } from "@/api/interface/system"
const props = defineProps({
  modelValue: Boolean,
  pid: { type: Number, default: 0 },
  row: { type: Object as PropType<SystemSpace.DeptTree>, default: () => {} },
  treeData: { type: Array as PropType<Array<SystemSpace.DeptTree>>, default: () => [] }
})
const emit = defineEmits(["update:modelValue", "refresh"])
// 参数
const formRef = ref<FormInstance>() // 表单实例
const depts = ref<any[]>([{ id: 0, name: "主类目", children: [] }]) // 部门信息
// 表单数据
const formValue = ref({
  pid: 0,
  name: "",
  sort: 1,
  leader: "",
  phone: "",
  email: "",
  status: 0
})
// 表单校验规则
const rules: FormRules = {}
// 事件
const commEvent = {
  // 关闭弹窗
  onClose: () => {
    emit("update:modelValue", false)
  },
  // 获取部门信息
  formatDept: (data: SystemSpace.DeptPageList[] | undefined): any[] => {
    if (!data || data.length <= 0) return []
    return data.map(item => ({
      id: item.id,
      name: item.name,
      children: commEvent.formatDept(item.children)
    }))
  },
  // 表单提交
  onSubmit: () => {
    if (!formRef.value) return
    formRef.value.validate(async valid => {
      if (!valid) return
      const params: SystemSpace.DeptAdd = { ...formValue.value }
      if (props.row?.id) {
        params.id = props.row.id
      }
      const { code } = await addDeptApi(params)
      if (code !== "200") return
      ElMessage.success("操作成功")
      commEvent.onClose()
      emit("refresh")
    })
  }
}
watch(
  () => props.modelValue,
  flag => {
    if (flag) {
      nextTick(() => {
        formRef.value?.resetFields()
        depts.value[0].children = commEvent.formatDept(props.treeData)
        if (props.row?.id) {
          const { pid, name, sort, leader, phone, email, status } = props.row
          formValue.value = { pid, name, sort, leader, phone, email, status }
        }
        formValue.value.pid = props.pid
      })
    }
  }
)
</script>

<style scoped></style>
